import axios from 'axios'
import { Toast } from 'vant'
import store from './../store'
import { getlocalStorageItem } from './auth'

const baseURL = process.env.NODE_ENV === 'production' ? 'http://121.36.89.156:6060' : '/api'

// 创建axios实例对象
const service = axios.create({
  baseURL, // url = base url + request url
  timeout: 5000 // request timeout
})

/* 请求拦截器（请求之前的操作） */
service.interceptors.request.use(
  // 是否需要设置 token
  config => {
    if (store.getters.token) {
      config.headers['X-Token'] = getlocalStorageItem('userInfo').token
    }
    return config
  },
  err => {
    return Promise.reject(err)
  })

/* 请求之后的操作 */
service.interceptors.response.use(
  response => {
    const res = response.data
    if (response.status === 200) {
      if (res.code === -1) {
        Toast({
          message: res.msg,
          type: 'error',
          duration: 5 * 1000
        })
      }
      return res
    } else {
      Toast({
        message: res.message,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.message || 'Error'))
    }
  },
  error => {
    if (error && error.stack.indexOf('timeout') > -1) {
      Toast({
        message: '请求超时',
        type: 'error',
        duration: 5 * 1000
      })
    } else {
      if (!error.response) {
        Toast({
          message: '服务器未作出响应，请刷新页面',
          type: 'error',
          duration: 5 * 1000
        })
        return Promise.reject('服务器未作出响应，请刷新页面')
      }
      switch (error.response.status) {
        case 401:
          Toast({
            message: '登录信息过期',
            type: 'error',
            duration: 5 * 1000
          })
          // sessionStorage.removeItem('token')
          this.$router.replace('/login')
          break
        case 403:
          Toast({
            message: '您没有权限进行此操作403',
            type: 'error',
            duration: 5 * 1000
          })
          break
        case 404:
          Toast({
            message: '后台接口地址有误',
            type: 'error',
            duration: 5 * 1000
          })
          break
        case 500:
          Toast({
            message: '服务器错误500',
            type: 'error',
            duration: 5 * 1000
          })
          break
        default:
          Toast({
            message: '未知错误',
            type: 'error',
            duration: 5 * 1000
          })
          return Promise.reject(error)
      }
    }

    return Promise.reject(error)
  }
)

export default service
